package com.brook.basicauth.controller;

import com.brook.basicauth.bean.UserBean;
import com.brook.basicauth.service.AuthService;
import com.brook.basicauth.util.MycConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Brook
 */
@RestController
@RequestMapping("/common/")
public class LoginController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private AuthService autService;

    @PostMapping("/login")
    public UserBean login(UserBean loginUser, HttpServletRequest request) {
        UserBean user = autService.userLogin(loginUser);
        if(null != user){
            logger.info("user login succeed");
            request.getSession().setAttribute(MycConstants.FLAG_CURRENT_USER, user);
        }
        logger.info("user login failed");
        return user;
    }

    @PostMapping("/getCurrentUser")
    public Object getCurrentUser(HttpSession session) {
        return session.getAttribute(MycConstants.FLAG_CURRENT_USER);
    }

    @PostMapping("/logout")
    public void logout(HttpSession session) {
        session.removeAttribute(MycConstants.FLAG_CURRENT_USER);
    }


}
